<template>
  <AxiomPlaygroundLayout :initial-sidebar-width="400">
    <template #default>
      <ChatPanel :messages="messages" :loading="isLoading" @send-message="handleSendMessage" />
    </template>
    
    <template #sidebar-content>
      <QuerySettingsPanel ref="settingsPanelRef" />
    </template>
  </AxiomPlaygroundLayout>
</template>

<script setup>
import { ref } from 'vue';
import { AxiomPlaygroundLayout } from 'axiom-view';
import { knowledgeSearchApi } from '@/api/knowledge/knowledgeSearch';
import ChatPanel from './components/ChatPanel.vue';
import QuerySettingsPanel from './components/QuerySettingsPanel.vue';

defineOptions({
  name: 'KnowledgeQueryView',
});

const settingsPanelRef = ref(null);
const messages = ref([]);
const isLoading = ref(false);

let messageIdCounter = 0;

async function handleSendMessage(queryText) {
  if (!settingsPanelRef.value) return;

  // 清空上一次的查询记录
  messages.value = [];
  messageIdCounter = 0;

  // 1. Add user message to chat
  messages.value.push({
    id: messageIdCounter++,
    role: 'user',
    content: queryText,
  });

  isLoading.value = true;

  try {
    // 2. Get current settings from sidebar
    const settings = settingsPanelRef.value.getSettings();
    if (!settings.kb_ids || settings.kb_ids.length === 0) {
      throw new Error("请至少选择一个知识库进行查询。");
    }

    // 3. Construct payload and call API
    const payload = {
      ...settings,
      query: queryText,
    };
    const res = await knowledgeSearchApi.searchDebug(payload);

    // 4. Add assistant response to chat
    if (res.success) {
      messages.value.push({
        id: messageIdCounter++,
        role: 'assistant',
        content: res.data, // 直接存储数据对象，而非字符串
      });
    } else {
       throw new Error(res.message || "API 请求失败");
    }
  } catch (error) {
    // 5. Handle errors
    messages.value.push({
      id: messageIdCounter++,
      role: 'assistant',
      content: JSON.stringify({
        error: "查询时发生错误",
        message: error.message,
      }, null, 2),
    });
  } finally {
    isLoading.value = false;
  }
}
</script> 